<script setup>
import {computed, getCurrentInstance, ref} from "vue";
import {showConfirmDialog, showSuccessToast, showToast} from 'vant';
import useStore from "@/store/index.js";
import {updateShopCart} from "@/api/cart.js"

const {userInfo} = useStore()
const user = computed(() => userInfo.userInfo)

const info = computed(() => JSON.parse(sessionStorage.getItem("goods-info")) || {})

const {proxy} = getCurrentInstance()
const showNorm = ref(false)
const activeNorm = ref(0)
const params = ref({
  number: 1,
  info: computed(() => info.value.goodsNorms.find((item, index) => index == activeNorm.value))
})

// 返回上级
const onClickLeft = () => {
  proxy.$router.back()
}

// 跳转方法
const linkToUrl = async (attr) => {
  // 检验用户是否登录
  if (!user.value.id) {
    showConfirmDialog({
      title: '提示',
      message:
          '监测到用户未登录,该操作需要用户登录完成后操作!!',
    })
        .then(() => {
          proxy.$router.push({path: "/login", query: {isBackUrl: "/goodsInfo"}})
        })
        .catch(() => {
          showToast('操作已取消');
        });
    return
  }
  switch (attr) {
    case "collect":
      await userInfo.collect({collectId: info.value.id, userId: user.value.id})
      showSuccessToast(!exist(user.value.collectList) ? "已取消收藏" : "收藏成功")
      break;
    case "joinCart":
      if(showNorm.value) {
        try {
          const cartParams = {
            goodsId: info.value.id,
            goodsNum: params.value.number,
            goodsNorm: params.value.info.desc,
            goodsPrice: info.value.price
          }
          await updateShopCart(cartParams)
          showSuccessToast("加入购物车完成")
          showNorm.value = false
        } catch (e) {
        }
      }else {
        showNorm.value = true
      }
      break;
    case "buyNow":
      console.log("立即购买")
      break;
  }

}

const exist = (val) => {
  if (!val) return false
  const splitArr = val.split(",").map(item => parseInt(item))
  return splitArr.includes(info.value.id)
}

</script>

<template>
  <van-nav-bar
      title="商品详情"
      left-arrow
      @click-left="onClickLeft"
  />
  <div class="content">
    <van-swipe :autoplay="5000" lazy-render>
      <van-swipe-item v-for="(item, index) in info.swipeInfo" :key="index">
        <van-image :src="item.url" class="w-full aspect-[6/5]">
          <template v-slot:loading>
            <van-loading type="spinner" size="20"/>
          </template>
        </van-image>
      </van-swipe-item>
    </van-swipe>
    <div class="p-[10px]">
      <div class="font-bold bg-[#fff] rounded-[5px] p-[10px]">
        <span class="text-[20px] text-[red]">${{ info.price.toFixed(2) }}起</span>
        <div class="text-[18px] my-[10px]">{{ info.title }}</div>
        <div class="flex justify-between text-[#ccc] text-[14px]">
          <span>库存 {{ info.stock }} 套</span>
          <span>销量: {{ info.sale }}套</span>
        </div>
      </div>
      <!--规格选择-->
      <van-cell :title="`已选择 : &nbsp;${params.info.desc}`" class="my-[10px]" is-link @click="showNorm = true"/>
      <van-action-sheet v-model:show="showNorm" title="配置选择">
        <div class="px-[10px] py-[20px] text-[16px]">
          <div class="flex">
            <van-image :src="info.banner" class="w-[100px] aspect-[1]">
              <template v-slot:loading>
                <van-loading type="spinner" size="20"/>
              </template>
            </van-image>
            <div class="ml-[20px] flex flex-col justify-between">
              <h5 class="text-[18px] font-bold">{{ info.title }}</h5>
              <div class="flex flex-col">
                <span class="text-[red]">￥{{ info.price.toFixed(2) }}</span>
                <span class="text-[#ccc]">库存: {{ info.stock }}</span>
              </div>
            </div>
          </div>
          <div class="my-[10px] flex flex-col">
            <span class="text-[#494949] text-[18px] font-bold mb-[10px]">规格:</span>
            <div v-for="(item,index) in info.goodsNorms" :key="index" class="mb-[10px] py-[5px] px-[10px]"
                 :class="{'active': activeNorm == index}"
                 @click="activeNorm = index"
            >
              {{ item.desc }}
            </div>
          </div>
          <div class="my-[10px] flex flex-col">
            <span class="text-[#494949] text-[18px] font-bold mb-[10px]">数量:</span>
            <div class="flex justify-end">
              <van-stepper v-model="params.number"/>
            </div>
          </div>
        </div>
      </van-action-sheet>
      <!--富文本区域-->
      <div class="bg-[#fff]" v-html="info.description"></div>
    </div>
  </div>
  <van-action-bar>
    <van-action-bar-icon icon="home-o" text="首页" to="/home"/>
    <van-action-bar-icon icon="cart-o" text="购物车" to="/cart"/>
    <van-action-bar-icon icon="star-o" text="收藏" :color="exist(user.collectList) ? '#ff5000' : ''"
                         @click="linkToUrl('collect')"/>
    <van-action-bar-button type="warning" text="加入购物车" @click="linkToUrl('joinCart')"/>
    <van-action-bar-button type="danger" text="立即购买" @click="linkToUrl('buyNow')"/>
  </van-action-bar>
</template>

<style scoped lang="scss">
.content {
  height: calc(100vh - 96px);
  overflow: auto;
  background-color: #f4f4f4;
}

:deep(.ql-indent-6) {
  img {
    margin: 0 auto;
  }
}

.active {
  border: 1px solid red;
  border-radius: 10px;
}
:deep(.van-popup--bottom) {
  bottom: 49px;
}

.van-action-bar {
  z-index: 9999;
}
</style>
